package com.sbtr.controller.algo;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sbtr.common.Response;
import org.springframework.web.bind.annotation.*;
import com.sbtr.exception.BDException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.sbtr.common.PageDto;
import com.sbtr.business.project.entity.AlgoPredictRecord;
import com.sbtr.business.project.dto.AlgoPredictRecordDto;
import com.sbtr.business.project.service.AlgoPredictRecordService;
import org.springframework.web.bind.annotation.RestController;
import com.sbtr.controller.common.CommonController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * 预测记录 前端控制器
 *
 * @author dgl
 * @since 2024-06-18
 */
@RestController
@RequestMapping("/algoPredictRecord")
@Api(tags = "预测记录")
public class AlgoPredictRecordController extends CommonController<AlgoPredictRecord, AlgoPredictRecordService> {

    @GetMapping("/pageList")
    @ApiOperation(httpMethod = "GET", value = "分页列表")
    public Response<PageDto<AlgoPredictRecord>> pageList(AlgoPredictRecordDto algoPredictRecordDto) {
        return Response.success(u.pageList(algoPredictRecordDto));
    }

    @PostMapping("/save")
    @ApiOperation(httpMethod = "POST", value = "保存")
    public Response<AlgoPredictRecord> save(@RequestBody AlgoPredictRecord algoPredictRecord) {
        algoPredictRecord.setId(null);
        if (algoPredictRecord.insert()) {
            return Response.success(algoPredictRecord);
        } else throw new BDException("保存失败");
    }

    @GetMapping("/downloadByTaskId")
    @ApiOperation(httpMethod = "GET", value = "根据任务id下载")
    public void downloadByTaskId(@RequestParam("taskId")String taskId, HttpServletResponse resp) throws IOException {
        QueryWrapper<AlgoPredictRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id", taskId);
        queryWrapper.last(" limit 1");
        queryWrapper.orderByDesc("create_time");
        AlgoPredictRecord algoPredictRecord = u.getOne(queryWrapper);
        // 读取本地文件的输入流
        File file = new File(algoPredictRecord.getPath());
        //下载
        try (
                InputStream in = Files.newInputStream(file.toPath());
                OutputStream out = resp.getOutputStream();
        ) {
            resp.setContentType("application/octet-stream");

            resp.setHeader("Content-Disposition", "attachment;" + " filename=" + URLEncoder.encode(algoPredictRecord.getName(), "utf-8"));
            // 把本地文件发送给客户端
            int byteRead = 0;
            byte[] buffer = new byte[512];
            while ((byteRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

